package calvin.study.redis.controller;

import java.util.Collections;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("seckill")
public class SeckillController {

	@Autowired
	private RedisTemplate<String, Object> redisTemplate;
	private final static String lua_script = "local lockSet = redis.call('setnx',KEYS[1],ARGV[1]) if lockSet == 1 then redis.call('expire',KEYS[1],ARGV[2]) end return lockSet ";

	@GetMapping("/doSeckill")
	public String doSeckill() {
		try {
			long flag = redisTemplate.execute(new DefaultRedisScript<>(lua_script, Long.class), Collections.singletonList("seckill-lock"),
					"Calvin", 10);
			if (0 == flag) {
				return "没秒到，请重试";
			} else {
				return "秒杀成功";
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			
		}
		return null;
	}

}
